package com.spring.component.framework.dao.intercepter;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @author liushihua
 * @since 2018年05月13日
 */
public class PostgreSqlHelper implements DialectHelper {

  @Override
  public Dialect getDialect() {
    return new PostgreSqlDialect();
  }

  /**
   * 得到最后一个Order By的插入点位置
   * 
   * @param selectSql 查询sql
   * @return 返回最后一个Order By插入点的位置
   */
  private static String getLastOrderInsertPoint(String selectSql) {
    int orderIndex = selectSql.toLowerCase().lastIndexOf("order by");
    return "";
  }

  /**
   * 得到SQL第一个正确的FROM的的插入点
   * 
   * @param selectSql
   * @return
   */
  private static int getFirstFromInsertPoint(String selectSql) {
    // 不区分大小写的匹配
    Pattern pattern = Pattern.compile("\\s+FROM\\s+", Pattern.CASE_INSENSITIVE);
    Matcher matcher = pattern.matcher(selectSql);
    while (matcher.find()) {
      int fromStartIndex = matcher.start();
      String text = selectSql.substring(0, fromStartIndex);
      if (isBracketCanPartnership(text)) {
        return fromStartIndex;
      }
    }
    return 0;
  }

  /**
   * 得到分页sql
   * 
   * @param selectSql 查询sql
   * @param offset start
   * @param limit rows
   * @return 分页sql
   */
  public static String getLimitString(String selectSql, int offset, int limit) {
    return getLineSql(selectSql) + "limit" + limit + "offset" + offset;
  }

  /**
   * 将SQL语句变成一条语句，并且每个单词的间隔都是1个空格
   * 
   * @param sql SQL语句
   * @return 如果sql是NULL返回空，否则返回转化后的SQL
   */
  private static String getLineSql(String sql) {
    return sql.replaceAll("[\r\n]", " ").replaceAll("\\s{2,}", " ");
  }

  /**
   * 判断括号"()"是否匹配,并不会判断排列顺序是否正确
   * 
   * @param text
   * @return
   */
  private static boolean isBracketCanPartnership(String text) {
    if (text != null) {
      int leftCount = 0;
      int rightCount = 0;
      for (char c : text.toCharArray()) {
        leftCount = c == 40 ? ++leftCount : leftCount;
        rightCount = c == 41 ? ++rightCount : rightCount;
      }
      return leftCount == rightCount;
    }
    return false;
  }

  public static void main(String[] args) {
    System.out.println(isBracketCanPartnership("(()(ad)sd)"));
  }
}
